package net.sppan.blog.controller.offer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sppan.blog.bean.VerificationRequestBean;
import net.sppan.blog.bean.VerificationResponseBean;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.model.User;
import net.sppan.blog.store.ConfigStore;
import net.sppan.blog.store.UserVerificationCache;
import net.sppan.blog.utils.AESUtil;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class UserVerificationController extends BaseController {
	private static Pattern pattern = Pattern.compile("^[0-9]*\\.*[0-9]*");

	public void index() {
		VerificationRequestBean requestBean = new VerificationRequestBean();
		try {
			requestBean = getRequestObject(VerificationRequestBean.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		User subUser = User.dao.findFirst("select * from sys_user where name = ? and pwd = ?", requestBean.getUserName(), requestBean.getUserPwd());
		boolean loginSuccess = true;
		boolean needUpdate = false;
		String userID = "";
		String updateUrl = "";
		if (subUser == null) {
			loginSuccess = false;
		} else if (subUser != null && StringUtils.isNotBlank(subUser.getHardware()) && !requestBean.getHardwareID().equals(subUser.getHardware())) {
			loginSuccess = false;
		} else {
			userID = subUser.getId().toString();
			String appVersion = requestBean.getAppVersion();
			String hardwareID = requestBean.getHardwareID();
			//判断是否是第一次登录，如果是，就把此设备的设备信息与subUser绑定
			if (StringUtils.isEmpty(subUser.getAppVersion()) || StringUtils.isEmpty(subUser.getHardware())) {
				subUser.setAppVersion(appVersion);
				subUser.setHardware(hardwareID);
				subUser.update();
			}
			UserVerificationCache.put(userID, subUser);
			//判断是否需要升级
			Matcher m = pattern.matcher(appVersion);
			if (m.matches() && Float.parseFloat(appVersion) < ConfigStore.instance.getConfig().getNewAppversion()) {
				needUpdate = true;
				String domain = ConfigStore.instance.getConfig().getDomainName();
				if (!domain.endsWith("/")) {
					domain += "/";
				}
				updateUrl = domain + "admin/sys/config/download?p=" + AESUtil.encrypt(System.currentTimeMillis() + "");
			}
		}

		VerificationResponseBean responseBean = new VerificationResponseBean();
		responseBean.setSuccess(loginSuccess);
		responseBean.setBan(false);
		responseBean.setNeedUpdate(needUpdate);
		responseBean.setUpdateUrl(updateUrl);
		responseBean.setUserID(userID);
		renderText(AESUtil.encrypt(JSONObject.toJSONString(responseBean)));
	}
}
